import { create } from 'zustand';

export type ToastType = 'success' | 'error' | 'warning' | 'info';

export interface Toast {
  id: string;
  type: ToastType;
  title?: string;
  message: string;
  duration?: number;
  action?: {
    label: string;
    onClick: () => void;
  };
}

interface ToastState {
  toasts: Toast[];
  addToast: (toast: Omit<Toast, 'id'>) => void;
  removeToast: (id: string) => void;
  clearToasts: () => void;
}

export const useToastStore = create<ToastState>((set, get) => ({
  toasts: [],

  addToast: toast => {
    const id = Math.random().toString(36).substr(2, 9);
    const newToast: Toast = {
      ...toast,
      id,
      duration: toast.duration ?? 5000,
    };

    set(state => ({
      toasts: [...state.toasts, newToast],
    }));

    // 自动移除 toast
    if (newToast.duration && newToast.duration > 0) {
      setTimeout(() => {
        get().removeToast(id);
      }, newToast.duration);
    }
  },

  removeToast: id => {
    set(state => ({
      toasts: state.toasts.filter(toast => toast.id !== id),
    }));
  },

  clearToasts: () => {
    set({ toasts: [] });
  },
}));

// 便捷的 toast 函数
export const toast = {
  success: (message: string, options?: Partial<Omit<Toast, 'id' | 'type' | 'message'>>) => {
    useToastStore.getState().addToast({ type: 'success', message, ...options });
  },

  error: (message: string, options?: Partial<Omit<Toast, 'id' | 'type' | 'message'>>) => {
    useToastStore.getState().addToast({ type: 'error', message, ...options });
  },

  warning: (message: string, options?: Partial<Omit<Toast, 'id' | 'type' | 'message'>>) => {
    useToastStore.getState().addToast({ type: 'warning', message, ...options });
  },

  info: (message: string, options?: Partial<Omit<Toast, 'id' | 'type' | 'message'>>) => {
    useToastStore.getState().addToast({ type: 'info', message, ...options });
  },
};
